package com.datn.activity;

import java.util.ArrayList;

import com.datn.DataAccess.FavouriteDatabaseAdapter;
import com.datn.DataAccess.InstructionDatabaseAdapter;
import com.datn.beans.FavouriteBean;
import com.datn.beans.UserBean;
import com.datn.utils.AlertCustom;
import com.datn.utils.BitmapUtils;
import com.datn.utils.NetworkUtils;
import com.datn.utils.PreferenceUtils;
import com.datn.utils.ScreenSizeUtils;
import com.datn.utils.places.DirectionObject;
import com.datn.utils.places.JsonDirection;
import com.datn.utils.places.Place;
import com.google.android.maps.GeoPoint;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class DetailsPlaceActivity extends Activity implements OnClickListener{

	Intent intent;

	Place placeReceived;//Variable for Save Place received in other activity
	/*String stCategory;*/

	TextView tvName;

	TextView tvAddress;
	TextView tvDistance;
	TextView tvPhone;
	TextView tvURL;

	Button btShowRoute;
	/*Button btShowOnMap;*/
	Button btShowRouteInstruction;
	Button btAddToContacts;
	Button btShareViaSMS;
	Button btShareViaEmail;

	ImageView imgViewStaticGoogleMap;
	public static final int PERCENT_DEFAUTL=70;
	public static final String COLOR_MARKER_DEFAULT="blue";
	private int width;//Width of static image
	private int height;//Height of static image
	

	public void getValueFromPreference(){
		try {
			placeReceived = PreferenceUtils.getPlaceDetail();
		} catch (Exception e) {
			// TODO: handle exception
			placeReceived=null;
		}
	}


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.details_place);
		PreferenceUtils.getInstance(this);	
		getValueFromPreference();

		tvName=(TextView) findViewById(R.id.tvNamePlaceDetailsPlace);

		tvAddress=(TextView) findViewById(R.id.tvAddressDetailsPlace);
		tvDistance=(TextView) findViewById(R.id.tvDistanceDetailsPlace);
		tvPhone=(TextView) findViewById(R.id.tvPhoneDetailsPlace);
		tvURL=(TextView) findViewById(R.id.tvURLDetailsPlace);

		if (placeReceived!=null){
			tvName.setText(placeReceived.getName());
			tvAddress.setText(placeReceived.getAddressLine());
			tvDistance.setText(placeReceived.getDistance());
			tvPhone.setText(placeReceived.getPhonenumber());
			tvURL.setText(placeReceived.getActualurl());
		}

		Log.v("DetailsPlace", "Lat:"+String.valueOf(placeReceived.getLatitude()));
		Log.v("DetailsPlace", String.valueOf(placeReceived.getLongtitude()));
		
		
		btShowRoute=(Button)findViewById(R.id.btShowRouteDetailsPlace);
		/*btShowOnMap=(Button)findViewById(R.id.btShowOnMapDetailsPlace);*/
		btShowRouteInstruction=(Button)findViewById(R.id.btShowRouteInstruction);
		btAddToContacts=(Button)findViewById(R.id.btSaveFavouriteDetailsPlace);
		btShareViaEmail = (Button)findViewById(R.id.btShareViaEmailDetailsPlace);
		btShareViaSMS = (Button) findViewById(R.id.btShareViaSMSDetailsPlace);


		//Set Listener for all
		btShowRoute.setOnClickListener(this);
		/*btShowOnMap.setOnClickListener(this);*/
		btShowRouteInstruction.setOnClickListener(this);
		btAddToContacts.setOnClickListener(this);
		btShareViaEmail.setOnClickListener(this);
		btShareViaSMS.setOnClickListener(this);

		tvPhone.setOnClickListener(this);
		tvURL.setOnClickListener(this);
	}


	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {


		//Click Button EVENT
		case R.id.btShowRouteDetailsPlace:
			//AlertCustom.showAlert(this, "OK", "Show Route");
			processShowRouteButton();
			break;

		case R.id.btSaveFavouriteDetailsPlace:
			/*AlertCustom.showAlert(this, "OK", "Add to Contacts");*/
			processSaveFavouriteButton();			
			break;

		case R.id.btShowRouteInstruction:
			/*AlertCustom.showAlert(this, "OK", "Instruction");*/
			processShowRouteInstructionButton();
			break;

			//Click TextView EVENT
		case R.id.tvPhoneDetailsPlace:
			processClickPhoneDetails();
			break;

		case R.id.tvURLDetailsPlace:
			//VALIDATE-EXPECTED
			processClickURLDetails();		
			break;

		case R.id.btShareViaEmailDetailsPlace:
			processShareViaEmailButton();
			break;

		case R.id.btShareViaSMSDetailsPlace:
			processShareViaSMSButton();
			break;

		default:
			break;
		}
	}






	private void processShareViaSMSButton() {
		// TODO Auto-generated method stub
		Uri smsUri = Uri.parse("tel:");
		Intent intent = new Intent(Intent.ACTION_VIEW, smsUri);
		String stBodySMS = "Name: "+ placeReceived.getName()+
				"\nAddress this place is: "+ placeReceived.getAddressLine()+
				"\nURL:"+ placeReceived.getActualurl() + 
				"\nPhone Number:"+ placeReceived.getPhonenumber() +					
				"\nYou can go to follow URL for see place in map:\n" + tvURL.getText() ;
		intent.putExtra("sms_body", stBodySMS);
		intent.setType("vnd.android-dir/mms-sms");				
		startActivity(intent);
	}


	private void processShareViaEmailButton() {
		// TODO Auto-generated method stub
		Intent i = new Intent(Intent.ACTION_SEND);  
		//i.setType("text/plain"); //use this line for testing in the emulator  
		i.setType("message/rfc822") ; // use from live device
		i.putExtra(Intent.EXTRA_EMAIL, new String[]{"@gmail.com"});  
		i.putExtra(Intent.EXTRA_SUBJECT,"Share location - "+placeReceived.getName());
		String stBodyEmail = "Name: "+ placeReceived.getName()+
				"\nAddress this place is: "+ placeReceived.getAddressLine()+
				"\nURL:"+ placeReceived.getActualurl() + 
				"\nPhone Number:"+ placeReceived.getPhonenumber() +					
				"\nYou can go to follow URL for see place in map:" + tvURL.getText() ;
		i.putExtra(Intent.EXTRA_TEXT, stBodyEmail);  
		startActivity(Intent.createChooser(i, "Select email application."));
	}


	private void processClickURLDetails() {
		// TODO Auto-generated method stub
		String stURL=tvURL.getText().toString().trim();
		if (!stURL.equalsIgnoreCase("")){
			Intent httpIntent = new Intent(Intent.ACTION_VIEW);
			httpIntent.setData(Uri.parse(stURL));
			startActivity(httpIntent); 
		}	
	}


	private void processClickPhoneDetails() {
		// TODO Auto-generated method stub
		String stPhone=tvPhone.getText().toString().trim();
		if (!stPhone.equalsIgnoreCase("")){
			stPhone=stPhone.replaceAll("[^0-9]", "");
			//Intent: CALL
			try {
				Intent intent = new Intent(Intent.ACTION_DIAL);
				intent.setData(Uri.parse("tel:"+stPhone)); //Pass Phone Number to ACTION DIAL
				startActivity(intent);
			} catch (Exception e) {
				/*AlertCustom.showAlert(this, "ERROR", "Call intent ERROR");*/
				Toast.makeText(this, "Call error", Toast.LENGTH_LONG).show();
			}
		}
	}


	private void processShowRouteInstructionButton() {
		// TODO Auto-generated method stub
		Intent intentInstruction = new Intent(this, DirectionInstructionActivity.class);
		startActivity(intentInstruction);
		finish();
	}


	private void processSaveFavouriteButton() {
		// TODO Auto-generated method stub
		StringBuilder sb = new StringBuilder();
		if (PreferenceUtils.isModeOnline()){
			//Toast.makeText(this, "ONLINE", Toast.LENGTH_LONG).show();
			long resultCreate = -1;
			FavouriteBean beanF = null;
			FavouriteDatabaseAdapter adapter = new FavouriteDatabaseAdapter(this);
			adapter.open();
			if (UserBean.isLogin){
				beanF = new FavouriteBean();
				//beanF.setDescription(placeReceived.get);
				//beanF.setEmail(placeReceived.get);
				beanF.setLatitude(placeReceived.getLatitude());
				beanF.setLongitude(placeReceived.getLongtitude());
				beanF.setPhonenumber(placeReceived.getPhonenumber());
				beanF.setUrl(placeReceived.getActualurl());
				beanF.setAddress(placeReceived.getAddressLine());
				beanF.setUsername(UserBean.username);
				beanF.setNameplace(placeReceived.getName());
					
					GeoPoint start = PreferenceUtils.getCurrentLocation();
					GeoPoint end = new GeoPoint((int)(placeReceived.getLatitude()*1E6), (int)(placeReceived.getLongtitude()));
					ScreenSizeUtils size=new ScreenSizeUtils(this);
					size.setSizePercentFollowDevice(80);
					int width = size.getWidth();
					int height = size.getWidth();
					
					Bitmap bitmap = BitmapUtils.getDirectionStaticImageGoogleMap(start, end, width, height);
					if (bitmap!=null)
						beanF.setImage(bitmap);
					
				resultCreate = adapter.createFavourite(beanF);
				if (resultCreate!=-1){
					Toast.makeText(this, "Save Favourite success!", Toast.LENGTH_LONG).show();
				}
				else {
					Toast.makeText(this, "This place added", Toast.LENGTH_LONG).show();
				}
				/*ArrayList<FavouriteBean> allRecent = adapter.getRecentPlaceWithUser(UserBean.username);
				for (int i = 0; i < allRecent.size(); i++) {
					sb.append("NameRecent:"+allRecent.get(i).getNameplace()+"\n");
				}*/
			}
			else{
				Toast.makeText(this, "You need login for using this function", Toast.LENGTH_LONG).show();
			}

			adapter.close();
			if (beanF!=null){
				if (resultCreate!=-1){
					FavouriteDatabaseAdapter adapterNew = new FavouriteDatabaseAdapter(this);
					adapterNew.open();
						int place_id = adapterNew.getPlaceIdFromLatLng(String.valueOf(beanF.getLatitude()), String.valueOf(beanF.getLongitude()));
						Log.v("PlaceIDDDDDDDDDDDD", String.valueOf(place_id));						
						GeoPoint startLocation = PreferenceUtils.getCurrentLocation();
						GeoPoint endLocation = new GeoPoint((int)(placeReceived.getLatitude()*1E6), (int)(placeReceived.getLongtitude()*1E6));
						JsonDirection jsonDirection=new JsonDirection(this, startLocation, endLocation);
						DirectionObject direction = jsonDirection.getDirectionFromJSON();
						ArrayList<String> allInstruction = direction.getInstructions();
					adapterNew.close();
					
					InstructionDatabaseAdapter adapterInstruction = new InstructionDatabaseAdapter(this);
					adapterInstruction.open();
						adapterInstruction.createInstruction(String.valueOf(place_id), allInstruction);
					adapterInstruction.close();
				}
			}
		}
		else{
			Toast.makeText(this, "This place added", Toast.LENGTH_LONG).show();
			/*FavouriteDatabaseAdapter adapter = new FavouriteDatabaseAdapter(this);
			adapter.open();
			if (UserBean.isLogin){
				ArrayList<FavouriteBean> allFavourite = adapter.getFavouritePlaceWithUser(UserBean.username);
				for (int i = 0; i < allFavourite.size(); i++) {
					sb.append("NameFavou:"+allFavourite.get(i).getNameplace()+"\n");
				}
			}
			Toast.makeText(this, sb.toString(), Toast.LENGTH_LONG).show();
			adapter.close();*/
		}
	}


	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub

		if (keyCode==KeyEvent.KEYCODE_BACK){
			Intent intent=new Intent(this, NearLocationActivity.class);
			startActivity(intent);
			finish();
		}

		return super.onKeyDown(keyCode, event);
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.details_menu, menu);
		return true;
	}


	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.itemHomeDetailsMenu:
			Intent intentHome = new Intent(this, NearLocationActivity.class);
			startActivity(intentHome);
			finish();
			break;
		case R.id.itemHelpDetailsMenu:
			processClickHelpMenu();
			break;			
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void processClickHelpMenu() {
		// TODO Auto-generated method stub
		
	}


	public void processShowRouteButton(){
		intent=new Intent(this, DirectionOnMapActivity.class);
		startActivity(intent);
		finish();
	}



}
